package cn.fzkj.framework.messagequece.config;

import cn.fzkj.common.ResultVO;
import cn.fzkj.framework.messagequece.MessageInfo;
import cn.fzkj.framework.messagequece.MessageType;
import cn.fzkj.project.common.service.impl.CommonServiceImpl;
import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = RabbitConfig.QUEUE_REDIS_RESOURCE_SERVER)
public class RabbitRecevier {
    private static final Logger log = LoggerFactory.getLogger(RabbitRecevier.class);
    @Autowired
    private CommonServiceImpl commonService;

    @RabbitHandler
    public void process(String content, Channel channel, Message message) throws IOException {
        // 拿到生产者中生成的uuid【消息的唯一id】
        String uuid = (String)message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
        // 成功消费消息 // 将消息从队列中移除
        // channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        // 消息消费失败
        // channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        MessageInfo messageInfo = new Gson().fromJson(content, MessageInfo.class);
        System.out.println(messageInfo);
        try{
            if (messageInfo.getMessageType() == MessageType.REDIS_GET_IMG){
                if (commonService.setImg2Redis()){
                    // 确认消息
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    log.info("ws rabbitmq consume msg： " + message.getMessageProperties().getDeliveryTag());
                }
            }else if (messageInfo.getMessageType() == MessageType.REDIS_GET_WORDS){

            }else {
                // 否认消息
                // 被否认的消息会重新放到队列中
                // 也可以使用 channel.basicReject()来绝收消息，被绝收的消息不会被重新放到队列
                if ((System.currentTimeMillis() - messageInfo.getCreateTime()) > 3000){
                    // 3s消息还没有被确认，手动确认，防止一直不停的重复发
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    log.error("3s ws rabbit not consume msg : {}", message.getMessageProperties().getDeliveryTag());
                }
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                log.info(" ws rabbitmq in queue again： " + content);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("receiver fail", e);
        }

    }

}
